var express = require('express');
var router = express.Router();

var Config=require('../../model/config.js').config;
var DB=require('../../model/db.js');

var md5=require('md5-node');

var bodyParser = require('body-parser');

router.use(bodyParser.urlencoded({ extended: false }));

router.use(bodyParser.json());

var multiparty=require('multiparty');

var ObjectId = require('mongodb').ObjectID;

/* GET users listing. */
router.get('/', function(req, res, next) {


  DB.find('user',{},function(err,data){

      var id=data._id;
      var username=data.username;
      var password=md5(data.password);
      var sex=data.sex;
      var age=data.age;
      //var add_time=getLocalTime(data.add_time);

    res.render('admin/user/index',{
      host:Config.HOST,
      list:data
    })
  })

});

router.get('/add', function(req, res, next) {
  res.render('admin/user/add',{
      host:Config.HOST
  })
});

router.post('/doAdd',function(req,res){
    console.log(req.body);
    var host=Config.HOST;
    var username=req.body.username;
    var password=md5(req.body.password);
    var age=req.body.age;
    var sex=req.body.sex;
    var date=new Date();
    var add_time=date.getTime();


    DB.insertOne('user',{
        username,
        password,
        age,
        sex,
        add_time

    },function(err,data){
        if(err){
          console.log('增加失败');
          return
        }

         res.redirect(host+'admin/user');
    })
})

router.get('/edit', function(req, res) {
    var id=req.query.id;
    console.log(id);
    DB.find('user',{'_id':new ObjectId(id)},function(err,data){
        console.log(data);
        res.render('admin/user/edit',{
            host:Config.HOST,
            info:data[0]
        })
    })
});

//执行编辑
router.post('/doEdit',function(req,res){
    var id=req.body.id;
    var username=req.body.username;
    var password=req.body.password;
    var sex=req.body.sex;
    var age=req.body.age;

    DB.updateOne('user',{'_id':new ObjectId(id)},{
        username,
        password,
        sex,
        age
    },function(err,data){
        res.redirect(HOST+'admin/user');
    })

})


//删除操作
router.get('/delete',function(req,res){
    var id=req.query.id;
    DB.deleteMany('user',{'_id':new ObjectId(id)},function(err,result){
        if(err){
          console.log(err);
        }else {
            res.render('admin/user/deletesuccess',{
                host:Config.HOST
            })
        }

    })

})


module.exports = router;
